package cn.ffcs.uec.outStaffDataModificationApply.action;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Component;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Messagebox;

import cn.ffcs.raptornuke.plugin.common.zk.ctrl.BasePortletComposer;
import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.raptornuke.portal.theme.ThemeDisplay;
import cn.ffcs.uec.common.util.NodeVoUtil;
import cn.ffcs.uec.common.util.UecConstants;
import cn.ffcs.uec.organization.manager.UecOrgOrgsManager;
import cn.ffcs.uec.organization.model.UecOrgOrgs;
import cn.ffcs.uec.outStaff.manager.UecOutStaffManager;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.outStaffDataModificationApply.action.bean.OutStaffTitleApprovalViewMainBean;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.manager.ActRunTaskManager;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.staff.manager.UecTitleManager;
import cn.ffcs.uec.staff.model.UecTitle;
import cn.ffcs.uec.staffRecords.vo.AtiOaBaseObject;
import cn.ffcs.uom.common.model.DefaultDaoFactory;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.NodeVo;

@Controller
@Scope("prototype")
public class OutStaffTitleApprovalViewMainComposer extends BasePortletComposer {

	private static final long serialVersionUID = -4065817692122212247L;

	private OutStaffTitleApprovalViewMainBean bean = new OutStaffTitleApprovalViewMainBean();

	private UecOutStaffManager uecOutStaffManager = (UecOutStaffManager) ApplicationContextUtil
			.getBean("uecOutStaffManager");

	private UecTitleManager uecTitleManager = (UecTitleManager) ApplicationContextUtil
			.getBean("uecTitleManager");

	private UecOrgOrgsManager uecOrgOrgsManager = (UecOrgOrgsManager) ApplicationContextUtil
			.getBean("uecOrgOrgsManager");

	private ActRunTaskManager actRunTaskManager = (ActRunTaskManager) ApplicationContextUtil
			.getBean("actRunTaskManager");

	/**
	 * 外包人员基本信息
	 */
	private UecOutStaffInfo outStaffInfo = UecOutStaffInfo.newInstance();

	private UecTitle uecTitle = UecTitle.newInstance();

	private String taskDefKey;

	private String opType;

	private String procDefKey;

	private String taskId;

	private AtiOaBaseObject oaBaseObject;

	@Override
	public String getPortletId() {
		return super.getPortletId();
	}

	@Override
	public ThemeDisplay getThemeDisplay() {
		return super.getThemeDisplay();
	}

	public void doAfterCompose(Component comp) throws Exception {
		super.doAfterCompose(comp);
		Components.wireVariables(comp, bean);

	}

	/**
	 * 界面初始化
	 */
	public void onCreate$outStaffTitleApprovalViewMainWin() {
		bandListbox();
		bindBean();
		this.checkTechposttitleIsNo();
	}

	/**
	 * 查看、编辑时判断是否是无专业技术职务
	 */
	public void checkTechposttitleIsNo() {
		String index = (String) bean.getPkTechposttitle().getSelectedItem()
				.getValue();
		// 若无专业技术职务名称，相关数据不可填
		if ("1001A1100000000006OJ".equals(index)) {
			bean.getGlbdef5().setDisabled(true);
			bean.getGlbdef1().setDisabled(true);
			bean.getGlbdef6().setDisabled(true);
			bean.getTitlerank().setDisabled(true);
			bean.getAssorg().setDisabled(true);
			bean.getTiptopFlag().setDisabled(true);
			bean.getCertifcode().setDisabled(true);
			bean.getGlbdef4().setDisabled(true);
			// 请数据
			bean.getGlbdef5().setSelectedIndex(0);
			bean.getGlbdef1().setValue(null);
			bean.getGlbdef6().setValue(null);
			bean.getTitlerank().setSelectedIndex(0);
			bean.getAssorg().setValue(null);
			bean.getTiptopFlag().setSelectedIndex(0);
			bean.getCertifcode().setValue(null);
			bean.getGlbdef4().setValue(null);
		}
	}

	/**
	 * 监听--获得职称
	 */
	public void onSelect$pkTechposttitle() {
		String index = (String) bean.getPkTechposttitle().getSelectedItem()
				.getValue();
		// 若无专业技术职务名称，相关数据不可填
		if ("1001A1100000000006OJ".equals(index)) {
			bean.getGlbdef5().setDisabled(true);
			bean.getGlbdef1().setDisabled(true);
			bean.getGlbdef6().setDisabled(true);
			bean.getTitlerank().setDisabled(true);
			bean.getAssorg().setDisabled(true);
			bean.getTiptopFlag().setDisabled(true);
			bean.getCertifcode().setDisabled(true);
			bean.getGlbdef4().setDisabled(true);
			// 请数据
			bean.getGlbdef5().setSelectedIndex(0);
			bean.getGlbdef1().setValue(null);
			bean.getGlbdef6().setValue(null);
			bean.getTitlerank().setSelectedIndex(0);
			bean.getAssorg().setValue(null);
			bean.getTiptopFlag().setSelectedIndex(0);
			bean.getCertifcode().setValue(null);
			bean.getGlbdef4().setValue(null);
		} else {
			bean.getGlbdef5().setDisabled(false);
			bean.getGlbdef1().setDisabled(false);
			bean.getGlbdef6().setDisabled(false);
			bean.getTitlerank().setDisabled(false);
			bean.getAssorg().setDisabled(false);
			bean.getTiptopFlag().setDisabled(false);
			bean.getCertifcode().setDisabled(false);
			bean.getGlbdef4().setDisabled(false);
		}
	}

	/**
	 * 重新申请
	 * 
	 * @throws InterruptedException
	 */
	public void onOk() throws InterruptedException {
		// 非查看历史工单
		if (!ApprovalConstants.OP_TYPE_VIEW.equals(opType)) {
			// 判断任务是否已被处理
			boolean isCompleted = ApprovalUtil.isTaskCompleted(oaBaseObject,
					taskId);
			if (isCompleted) {
				onCancel();
				Events.postEvent(ApprovalConstants.ON_REFRESH_QUERY_RESPONSE,
						this.self, null);
				ZkUtil.showError("任务不存在或已被处理完毕！", "错误提示");
				return;
			}
			// 添加校验
			String msg = this.checkUacStaffData();
			if (null != msg) {
				Messagebox.show(msg);
				return;
			}
			Messagebox.show("是否提交审批？", "输入确认提示", Messagebox.OK
					| Messagebox.CANCEL, Messagebox.QUESTION,
					new EventListener() {
						@Override
						public void onEvent(Event event) throws Exception {
							if (((Integer) event.getData()).intValue() == Messagebox.OK) {
								postApprovalData();
								onCancel();
							} else {
								return;
							}
						}
					});
		} else {
			this.onCancel();
		}

	}

	/**
	 * 重新提交数据
	 * 
	 * @throws InterruptedException
	 */
	public void postApprovalData() throws InterruptedException {
		String currentName = ApprovalUtil.getCurrentName();
		if (StrUtil.isNullOrEmpty(currentName)) {
			ZkUtil.showError("当前登录用户已失效，请重新登录!", "错误提示");
			return;
		}

		PubUtil.fillPoFromBean(bean, uecTitle);
		uecTitle.setGlbdef4(DateUtil.dateToStr(bean.getGlbdef4().getValue()));
		uecTitle.setModifiedtime(DateUtil.getCurrenDate());
		uecTitle.setModifier(currentName);
		DefaultDaoFactory.getDefaultDao().updateObject(uecTitle);

		Events.postEvent("onOKResponse", this.self,
				ApprovalConstants.ON_OK_RESULT);

	}

	/**
	 * 审批同意
	 * 
	 * @throws InterruptedException
	 */
	public void onApproval() throws InterruptedException {
		Messagebox.show("是否提交审批？", "输入确认提示", Messagebox.OK | Messagebox.CANCEL,
				Messagebox.QUESTION, new EventListener() {
					@Override
					public void onEvent(Event event) throws Exception {
						if (((Integer) event.getData()).intValue() == Messagebox.OK) {
							approvalData();
						} else {
							return;
						}
					}
				});
	}

	public void approvalData() {
		Map<String, Object> map = new HashMap<String, Object>();
		String comment = this.getComment(taskDefKey);
		map.put("comment", comment);
		map.put("onApprovalResult", ApprovalConstants.ON_APPROVAL_RESULT);
		Events.postEvent("onApprovalResponse", this.self, map);
		this.onCancel();

	}

	/**
	 * 审批拒绝
	 */
	public void onReject() {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("comment", this.getComment(taskDefKey));
		map.put("onRejectResult", ApprovalConstants.ON_REJECT_RESULT);
		Events.postEvent("onRejectResponse", this.self, map);
		this.onCancel();
	}

	/**
	 * 关闭弹窗
	 */
	public void onCancel() {
		this.bean.getOutStaffTitleApprovalViewMainWin().onClose();
	}

	/**
	 * 获取传值
	 * 
	 * @throws ParseException
	 * @throws WrongValueException
	 */
	private void bindBean() {
		String procDefName = (String) arg.get("procDefName");
		this.bean.getOutStaffTitleApprovalViewMainWin().setTitle(
				procDefName + "审批");

		oaBaseObject = (AtiOaBaseObject) arg.get("oaBaseObject");
		if (!StrUtil.isNullOrEmpty(oaBaseObject)) {
			// 获取审批意见
			PubUtil.fillBeanFromPo(oaBaseObject, bean);
		}
		opType = (String) arg.get("opType");
		if ("onView".equals(opType)) {
			// 查看历史工单
			setButtonValid(true, false, false);
			setTextValid(true, true, true);
		} else {

			taskDefKey = (String) arg.get("taskDefKey");
			if ("modify".equals(taskDefKey)) {
				setButtonValid(true, false, false);
				setTextValid(false, false, false);
			} else {
				setButtonValid(false, true, true);
			}
			if ("deptLeaderAudit".equals(taskDefKey)) {
				this.bean.getSecondText().setRows(2);
				this.setTextValid(true, false, false);
				bean.getSecondText().setValue(null);
			}
			if ("hrAudit".equals(taskDefKey)) {
				this.bean.getThirdText().setRows(2);
				this.setTextValid(false, true, false);
				bean.getThirdText().setValue(null);
			}
			if ("hrLeaderAudit".equals(taskDefKey)) {
				this.bean.getFourthText().setRows(2);
				this.setTextValid(false, false, true);
				bean.getFourthText().setValue(null);
			}
		}

		taskId = (String) arg.get("taskId");
		opType = (String) arg.get("opType");
		procDefKey = (String) arg.get("procDefKey");
		if (null != oaBaseObject) {

			List<Map<String, Object>> list = actRunTaskManager
					.getRuTasks(oaBaseObject.getProcInstId());
			if (null == list) {
				ZkUtil.showError("未知错误!", "错误信息");
				return;
			}
			if (list.size() == 0) {
				if (ApprovalUtil.OUT_STAFF_TITLE_EDIT.equals(procDefKey)) {
					String titleIdTmp = oaBaseObject.getTitleId();
					oaBaseObject.setTitleId(oaBaseObject.getTitleIdHis());
					oaBaseObject.setTitleIdHis(titleIdTmp);
				}
			}

			// 2.获取人员信息
			String outStaffId = oaBaseObject.getOutStaffId();
			outStaffInfo.setOutStaffId(Long.parseLong(outStaffId));
			outStaffInfo = uecOutStaffManager
					.findUecOutStaffInfoByOutStaffId(outStaffInfo);
			if (null != outStaffInfo) {
				PubUtil.fillBeanFromPo(outStaffInfo, bean);
				UecOrgOrgs newOrgOrgs = UecOrgOrgs.newInstance();
				newOrgOrgs.setPkOrg(outStaffInfo.getPkHrorg());
				newOrgOrgs = uecOrgOrgsManager
						.findUecOrgOrgsByUecOrgOrgs(newOrgOrgs);
				if (null != newOrgOrgs) {
					bean.getOrgName().setValue(newOrgOrgs.getName());
				}
			}
			// 专业技术职务分新增和修改，如果是修改流程又对比信息，如果是新增流程无对比信息
			if (ApprovalUtil.OUT_STAFF_TITLE_EDIT.equals(procDefKey)) {
				String titleIdHis = oaBaseObject.getTitleIdHis();
				uecTitle = new UecTitle();
				uecTitle.setTitleId(Long.valueOf(titleIdHis));
				uecTitle = uecTitleManager.findUecTitleById(uecTitle);
				bean.getAssorgHis().setValue(uecTitle.getAssorg());
				bean.getCertifcodeHis().setValue(uecTitle.getCertifcode());
				bean.getGlbdef1His().setValue(uecTitle.getGlbdef1());
				bean.getGlbdef4His().setValue(uecTitle.getGlbdef4());
				bean.getGlbdef5His().setValue(uecTitle.getGlbdef5Name());
				bean.getGlbdef6His().setValue(uecTitle.getGlbdef6());
				// 获得职称
				bean.getPkTechposttitleHis().setValue(
						uecTitle.getPkTechposttitleName());
				// 最高
				if ("Y".equals(uecTitle.getTiptopFlag())) {
					bean.getTiptopFlagHis().setValue("是");
				} else if ("N".equals(uecTitle.getTiptopFlag())) {
					bean.getTiptopFlagHis().setValue("否");
				} else {
					bean.getTiptopFlagHis().setValue(null);
				}
				// 职称等级
				bean.getTitlerankHis().setValue(uecTitle.getTitlerankName());
			}
			if (ApprovalUtil.OUT_STAFF_TITLE_ADD.equals(procDefKey)) {
				bean.getGroupboxHis().setVisible(false);
			}

			// 获取审批中人员专业技术职务信息
			String titleId = oaBaseObject.getTitleId();
			uecTitle.setTitleId(Long.valueOf(titleId));
			uecTitle = uecTitleManager.findUecTitleById(uecTitle);
			if (null != uecTitle) {
				PubUtil.fillBeanFromPo(uecTitle, bean);
				// // 获得职称
				// @SuppressWarnings("unchecked")
				// List<Listitem> pkTechposttitleItem =
				// bean.getPkTechposttitle()
				// .getChildren();
				// for (Listitem listitem : pkTechposttitleItem) {
				// if (null != listitem
				// && !StrUtil.isNullOrEmpty(listitem.getValue())) {
				// if (listitem
				// .getValue()
				// .toString()
				// .equals(uecTitle.getPkTechposttitle()
				// .toString())) {
				// bean.getPkTechposttitle().setSelectedItem(listitem);
				// break;
				// }
				// }
				// }
				// // 取得资格途径
				// @SuppressWarnings("unchecked")
				// List<Listitem> glbdef5Item = bean.getGlbdef5()
				// .getChildren();
				// for (Listitem listitem : glbdef5Item) {
				// if (null != listitem
				// && !StrUtil.isNullOrEmpty(listitem.getValue())) {
				// if (listitem
				// .getValue()
				// .toString()
				// .equals(uecTitle.getGlbdef5().toString())) {
				// bean.getGlbdef5().setSelectedItem(listitem);
				// break;
				// }
				// }
				// }
				// 取得资格时间
				bean.getGlbdef4().setValue(
						DateUtil.patternStrToDate(uecTitle.getGlbdef4()));

			}
		}

	}

	/**
	 * 获取审批意见
	 * 
	 * @param taskDefKey
	 * @return
	 */
	private String getComment(String taskDefKey) {
		if ("deptLeaderAudit".equals(taskDefKey)) {
			return this.bean.getSecondText().getValue();
		}
		if ("hrAudit".equals(taskDefKey)) {
			return this.bean.getThirdText().getValue();
		}
		if ("hrLeaderAudit".equals(taskDefKey)) {
			return this.bean.getFourthText().getValue();
		}
		return null;
	}

	/**
	 * 设置按钮
	 * 
	 * @param canEdit
	 * @param canApproval
	 * @param canReject
	 */
	private void setButtonValid(boolean canEdit, boolean canApproval,
			boolean canReject) {
		this.bean.getOkBtn().setVisible(canEdit);
		this.bean.getOkBtn().setDisabled(!canEdit);

		this.bean.getApprovalBtn().setVisible(canApproval);
		this.bean.getApprovalBtn().setDisabled(!canApproval);

		this.bean.getRejectBtn().setVisible(canReject);
		this.bean.getRejectBtn().setDisabled(!canReject);

	}

	/**
	 * 设置审批意见栏
	 * 
	 * @param secondCanEdit
	 * @param thirdCanEdit
	 * @param fourthCanEdit
	 */
	private void setTextValid(boolean secondCanEdit, boolean thirdCanEdit,
			boolean fourthCanEdit) {
		this.bean.getSecondText().setDisabled(!secondCanEdit);
		this.bean.getThirdText().setDisabled(!thirdCanEdit);
		this.bean.getFourthText().setDisabled(!fourthCanEdit);
	}

	private void bandListbox() {

		// 取得资格途径glbdef5
		ListboxUtils.rendererForEdit(bean.getGlbdef5(),
				NodeVoUtil.getDictionaries(UecConstants.ACCESS_QUALOFICATION));
		// 职称等级titlerank
		ListboxUtils.rendererForEdit(bean.getTitlerank(),
				NodeVoUtil.getDictionaries(UecConstants.TITLE_RANK));
		// 职称
		ListboxUtils.rendererForEdit(bean.getPkTechposttitle(),
				NodeVoUtil.getDictionaries(UecConstants.TITLE_NAME));
		// 绑定 最高
		List<NodeVo> nodeVoTiptopFlag = new ArrayList<NodeVo>();
		String[][] tiptopFlag = { { "Y", "是" }, { "N", "否" } };
		for (int i = 0; i < tiptopFlag.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(tiptopFlag[i][j]);
				nodeVo.setName(tiptopFlag[i][j + 1]);
			}
			nodeVoTiptopFlag.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getTiptopFlag(), nodeVoTiptopFlag);
	}

	/**
	 * 检测填入的参数是否为空
	 */
	private String checkUacStaffData() {
		if (!"1001A1100000000006OJ".equals(bean.getPkTechposttitle()
				.getSelectedItem().getValue())) {
			if (StrUtil.isNullOrEmpty(bean.getGlbdef5().getSelectedItem()
					.getValue())) {
				return "请选择取得资格途径";
			} else if (StrUtil.isNullOrEmpty(bean.getGlbdef1().getValue())) {
				return "请填写聘任情况";
			} else if (StrUtil.isNullOrEmpty(bean.getGlbdef6().getValue())) {
				return "请填写资格审批单位";
			} else if (StrUtil.isNullOrEmpty(bean.getTitlerank()
					.getSelectedItem().getValue())) {
				return "请选择职称等级";
			} else if (StrUtil.isNullOrEmpty(bean.getAssorg().getValue())) {
				return "请填写评定机构";
			} else if (StrUtil.isNullOrEmpty(bean.getGlbdef4().getValue())) {
				return "请选择获取职业资格时间";
			}
		}
		return null;
	}

}
